"use client";
import { useState, useEffect } from "react";
import NavBar from "@/app/components/NavBar";
import Footer from "@/app/components/Footer";
import VideoCard from "@/app/components/VideoCard";
import { VideoItem } from "@/app/types/video";

export default function FavoritesPage() {
  const [favorites, setFavorites] = useState<VideoItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  
  // 模拟用户ID（实际项目中应该从认证系统获取）
  const userId = 1;
  const pageSize = 20;
  
  const fetchFavorites = async (pageNum: number = 1) => {
    setLoading(true);
    try {
      const response = await fetch(`/api/favorites?userId=${userId}&page=${pageNum}&size=${pageSize}`);
      const data = await response.json();
      
      if (data.success) {
        if (pageNum === 1) {
          setFavorites(data.data);
        } else {
          setFavorites(prev => [...prev, ...data.data]);
        }
        // 如果返回的数据少于请求的数量，说明没有更多数据了
        setHasMore(data.data.length === pageSize);
      } else {
        setError(data.message || '获取收藏列表失败');
      }
    } catch (err) {
      console.error('获取收藏列表失败:', err);
      setError('获取收藏列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };
  
  useEffect(() => {
    fetchFavorites();
  }, []);
  
  const handleLoadMore = () => {
    if (!loading && hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      fetchFavorites(nextPage);
    }
  };
  
  const handleRefresh = () => {
    setPage(1);
    fetchFavorites(1);
  };
  
  const handleVideoDeleted = () => {
    // 刷新列表
    handleRefresh();
  };
  
  return (
    <div className="min-h-screen">
      <NavBar />
      <main className="mx-auto w-full max-w-5xl px-4 py-6">
        <div className="mb-6">
          <h1 className="text-2xl font-bold mb-2">我的收藏</h1>
          <p className="text-zinc-500 dark:text-zinc-400">
            您收藏了 {favorites.length} 个视频
          </p>
        </div>
        
        {error && (
          <div className="mb-6 p-4 bg-red-100 text-red-800 rounded-md dark:bg-red-900 dark:text-red-100">
            {error}
            <button 
              onClick={handleRefresh}
              className="ml-2 text-sm text-red-600 underline hover:text-red-800 dark:text-red-300 dark:hover:text-red-100"
            >
              重试
            </button>
          </div>
        )}
        
        {loading && favorites.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-zinc-500 dark:text-zinc-400">加载收藏列表中...</p>
          </div>
        ) : favorites.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-zinc-500 dark:text-zinc-400">您还没有收藏任何视频</p>
          </div>
        ) : (
          <>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {favorites.map(video => (
                <VideoCard 
                  key={video.id} 
                  video={video} 
                  refreshVideos={handleVideoDeleted}
                />
              ))}
            </div>
            
            {hasMore && (
              <div className="mt-8 text-center">
                <button
                  onClick={handleLoadMore}
                  disabled={loading}
                  className={`px-4 py-2 rounded-md ${loading 
                    ? 'bg-zinc-200 text-zinc-500 cursor-not-allowed dark:bg-zinc-800'
                    : 'bg-zinc-100 text-zinc-700 hover:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700'
                  }`}
                >
                  {loading ? '加载中...' : '加载更多'}
                </button>
              </div>
            )}
          </>
        )}
      </main>
      <Footer />
    </div>
  );
}